//
//  PPAlbumFetcher.m
//  pickpic
//
//  Created by Jinxiao on 9/25/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumFetcher.h"

@interface PPAlbumFetcher ()

@property (readwrite, nonatomic, strong) void (^completion) (NSArray *results, NSError *error);

@end

@implementation PPAlbumFetcher

- (void)dealloc {
    
}

- (void)fetchAllAlbumsWithCompletion:(void (^)(NSArray *, NSError *))completion {
    [self fetchAlbumsWithIndex:1 count:100 completion:completion];
}

- (void)fetchAlbumsWithIndex:(NSInteger)index count:(NSInteger)count completion:(void (^)(NSArray *, NSError *))completion {

    [PPNetworkService fetchMyAlbumsWithKeyword:nil ablumIDs:nil tagID:nil isHotTag:nil owner:DGCurrentAccount.userID pageSize:count pageIndex:index callback:^(id data, NSError *error) {

        if(error == nil) {

            NSArray *albums = [data validArray];

            NSMutableArray *results_ = [NSMutableArray array];

            [results_ addObjectsFromArray:albums];

            if(albums.count < count) {
                !completion ?: completion(results_, nil);
            } else {
                [self fetchAlbumsWithIndex:index + count count:count completion:^(NSArray *results, NSError *error) {

                    if(error == nil) {
                        [results_ addObjectsFromArray:results];

                        !completion ?: completion(results_, nil);
                    } else {
                        !completion ?: completion(nil, error);
                    }
                    
                }];
            }
        } else {
            !completion ?: completion(nil, error);
        }
    }];

}

@end
